package co.baiku.boot.security.filter;

import co.baiku.boot.common.tools.StringTools;
import co.baiku.boot.config.JwtConfig;
import co.baiku.boot.core.orm.dto.UserDetailDto;
import co.baiku.boot.tools.JwtTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private JwtConfig jwtConfig;
    private JwtTools jwtTools = JwtTools.ME;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String auth_token = request.getHeader(jwtConfig.getHeader());
        final String auth_token_start = "Bearer ";
        if (StringTools.isBlank(auth_token)) {
            auth_token = null;
        } else if (auth_token.startsWith(auth_token_start)) {
            auth_token = auth_token.substring(auth_token_start.length());
        }
        String username = jwtTools.getUsernameFromToken(auth_token);
        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            UserDetailDto user = jwtTools.getUserFromToken(auth_token);
            if (jwtTools.validateToken(auth_token, user)) {
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        chain.doFilter(request, response);
    }
}
